1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.io;
18  
19  import com.google.common.annotations.Beta;
20  
21  import java.io.FilterOutputStream;
22  import java.io.IOException;
23  import java.io.OutputStream;
24  
25  import javax.annotation.Nullable;
26  
27  /**
28   * An OutputStream that counts the number of bytes written.
29   *
30   * @author Chris Nokleberg
31   * @since 1.0
32   */
33  @Beta
34  public final class CountingOutputStream extends FilterOutputStream {
35  
36    private long count;
37  
38    /**
39     * Wraps another output stream, counting the number of bytes written.
40     *
41     * @param out the output stream to be wrapped
42     */
43    public CountingOutputStream(@Nullable OutputStream out) {
44      super(out);
45    }
46  
47    /** Returns the number of bytes written. */
48    public long getCount() {
49      return count;
50    }
51  
52    @Override public void write(byte[] b, int off, int len) throws IOException {
53      out.write(b, off, len);
54      count += len;
55    }
56  
57    @Override public void write(int b) throws IOException {
58      out.write(b);
59      count++;
60    }
61  
62    // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior:
63    // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream.
64    // It should flush itself if necessary.
65    @Override public void close() throws IOException {
66      out.close();
67    }
68  }